<template>
  <div class="controls-item">
    <div @click="addsatellite">
      <i class="iconfont icon-satellite"></i>卫星
    </div>
    <div>
      <i class="iconfont icon-wumai"></i>空气
    </div>
    <div>
      <i class="iconfont icon-traffic"></i>路况
    </div>
    <div @click="toggleMeasure" :class="{ active: ismeassure }">
      <i class="iconfont icon-ranging"></i>测距
    </div>
    <div @click="toggleFullscreen">
      <i class="iconfont icon-fullscreen-expand"></i>全屏
    </div>
  </div>

  <!-- 路网 -->
  <div v-if="isnetworkshow" class="road-network">
    <el-checkbox v-model="isnetwork" @change="toggleRoadNet">路网</el-checkbox>
  </div>
</template>

<script setup>
import { ref, inject, watch, onUnmounted } from "vue";
import screenfull from 'screenfull'; // 引入全屏库

const { Amap, map } = inject('mapandAmap')

// 状态变量
let isstatellite = ref(true)
let isnetwork = ref(false)
let isnetworkshow = ref(false)
let ismeassure = ref(false) // 控制测距工具的启用状态
let isFullscreen = ref(false) // 控制全屏状态

// 地图图层和工具实例
let statellite, roadNet, mouseTool = null
let measureElements = ref([]) // 保存所有测距相关元素，用于完整清除

// 测距工具配置项（单独提取，便于复用）
const measureOptions = {
  startMarkerOptions: {
    icon: null, // 后续在初始化时设置
    offset: null
  },
  endMarkerOptions: {
    icon: null,
    offset: null
  },
  midMarkerOptions: {
    icon: null,
    offset: null
  },
  lineOptions: {
    strokeStyle: "solid",
    strokeColor: "#FF33FF",
    strokeOpacity: 1,
    strokeWeight: 2,
  }
}

// 初始化地图工具
watch([Amap, map], () => {
  if (Amap.value && map.value && !mouseTool) {
    // 创建卫星图层
    statellite = new Amap.value.TileLayer.Satellite()
    // 创建路网图层
    roadNet = new Amap.value.TileLayer.RoadNet();
    // 创建测距工具
    mouseTool = new Amap.value.MouseTool(map.value);
    
    // 完善测距配置（使用实际的Amap对象）
    measureOptions.startMarkerOptions.icon = new Amap.value.Icon({
      size: new Amap.value.Size(19, 31),
      imageSize: new Amap.value.Size(19, 31),
      image: "//webapi.amap.com/theme/v1.3/markers/b/start.png",
    })
    measureOptions.startMarkerOptions.offset = new Amap.value.Pixel(-9, -31)
    
    measureOptions.endMarkerOptions.icon = new Amap.value.Icon({
      size: new Amap.value.Size(19, 31),
      imageSize: new Amap.value.Size(19, 31),
      image: "//webapi.amap.com/theme/v1.3/markers/b/end.png",
    })
    measureOptions.endMarkerOptions.offset = new Amap.value.Pixel(-9, -31)
    
    measureOptions.midMarkerOptions.icon = new Amap.value.Icon({
      size: new Amap.value.Size(19, 31),
      imageSize: new Amap.value.Size(19, 31),
      image: "//webapi.amap.com/theme/v1.3/markers/b/mid.png",
    })
    measureOptions.midMarkerOptions.offset = new Amap.value.Pixel(-9, -31)

    // 监听绘制事件，保存所有创建的元素
    mouseTool.on('draw', (e) => {
      if (e.obj) {
        measureElements.value.push(e.obj);
      }
    });
  }
}, { immediate: true })

// 监听测距状态变化
watch(ismeassure, (newVal) => {
  if (!mouseTool || !map.value || !Amap.value) return;

  if (newVal) {
    // 开启测距功能 - 确保是全新状态
    startMeasure();
  } else {
    // 关闭测距功能 - 彻底清理
    stopMeasure();
  }
})

// 启动测距功能
function startMeasure() {
  // 确保先清除可能存在的残留元素
  clearMeasureElements();
  
  // 启动测距工具
  mouseTool.rule(measureOptions);
  
  // 更改鼠标样式，提示用户处于测距模式
  map.value.setDefaultCursor("crosshair");
}

// 停止测距功能
function stopMeasure() {
  // 关闭工具并清除默认内容
  mouseTool.close(true);
  
  // 额外清除所有相关元素
  clearMeasureElements();
  
  // 恢复鼠标样式
  map.value.setDefaultCursor("default");
}

// 清除所有测距相关元素
function clearMeasureElements() {
  if (map.value && measureElements.value.length > 0) {
    measureElements.value.forEach(element => {
      if (map.value.hasLayer(element)) {
        map.value.remove(element);
      }
    });
    measureElements.value = [];
  }
}

// 组件卸载时清理
onUnmounted(() => {
  if (mouseTool) {
    mouseTool.close(true);
  }
  clearMeasureElements();
})

// 卫星图层切换
function addsatellite() {

    if (isstatellite.value) {
      map.value.add(statellite)
      isstatellite.value = false
      isnetworkshow.value = true
    } else {
        isstatellite.value = true
          isnetworkshow.value = false
         map.value.getLayers().forEach(item => {
        if (item.CLASS_NAME === 'AMap.TileLayer.Satellite') {
          map.value.remove(item)
        }
         })
    }
  
}

// 路网图层切换
function toggleRoadNet() {

    if (isnetwork.value) {
      map.value.add(roadNet)
    } else {
     map.value.getLayers().forEach(item => {
        if (item.CLASS_NAME === 'AMap.TileLayer.RoadNet') {
          map.value.remove(item)
        }
     })
    }
  
}

// 测距工具切换
function toggleMeasure() {
  ismeassure.value = !ismeassure.value
}

// 全屏切换
function toggleFullscreen() {
  if (!screenfull.isEnabled) {
    console.error('全屏功能不被浏览器支持');
    return;
  }

  if (isFullscreen.value) {
    screenfull.exit();
    isFullscreen.value = false;
  } else {
    screenfull.request();
    isFullscreen.value = true;
  }
}

// 监听全屏状态变化
screenfull.on('change', () => {
  isFullscreen.value = screenfull.isFullscreen;
});
</script>

<style lang="scss" scoped>
.controls-item {
  position: fixed;
  padding: 0 20px;
  top: 50px;
  right: 100px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 50px;
  width: 450px;
  background-color: rgb(255, 255, 255);
  border-radius: 5px;
  z-index: 100;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  div {
    padding: 5px 10px;
    color: rgb(124, 129, 150);
    font-size: 17px;
    height: 50px;
    line-height: 50px;
    cursor: pointer;
    transition: all 0.3s;
    i {
      font-size: 22px;
      margin-right: 10px;
    }
  }

  div:hover, div.active {
    color: rgb(54, 162, 255);
  }
}

.road-network {
  position: fixed;
  text-align: center;
  top: 50px;
  right: 600px;
  height: 50px;
  line-height: 50px;
  width: 70px;
  background-color: rgb(255, 255, 255);
  border-radius: 5px;
  z-index: 100;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>